package com.hdl.servlet.mallcomment;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hdl.entity.HdlUser;
import com.hdl.entity.MallComment;
import com.hdl.service.CommentService;
import com.hdl.service.impl.CommentServiceImpl;

/**
 * CommentServlet 用户评论
 * @author Administrator
 *
 */
@WebServlet("/commentAdd.let")
public class CommentServlet extends HttpServlet{

	private CommentService service = new CommentServiceImpl();
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		//获取参数
		String message = req.getParameter("mallCommentMessage");
		String id = req.getParameter("mallProductId");
		
		//获取用户对象
		HdlUser user = (HdlUser) req.getSession().getAttribute("user");
		
		//创建评论对象
		MallComment comment = new MallComment();
		
		//属性赋值
		comment.setHdlUserId(user.getHdlUserId());
		//comment.setMallCommentId(null);//自增长
		comment.setMallCommentMessage(message);
		comment.setMallCommentTime(new Date());
		comment.setMallProductId(id);
		
		Map<String,Object> map = new HashMap<String,Object>();
		ObjectMapper mapper = new ObjectMapper();
		
		//调用业务逻辑接口
		try {
		service.addComment(comment);
		}catch(Exception e) {
			e.printStackTrace();
			map.put("code", 1);
			map.put("msg", "发表失败");
			mapper.writeValue(resp.getOutputStream(), map);
			return;
		}
		
		map.put("code",2);
		map.put("mgs","发送成功");
		//写回消息
		mapper.writeValue(resp.getOutputStream(), map);
		
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
}
